#include "collection.h"
#include "util.h"

#include <new>

Collection::Collection()
{
	xmlNode *root;
	_selected = -1;

	_xmlDoc = xmlNewDoc( (const xmlChar*) "1.0" );
	root = xmlNewNode( NULL, (const xmlChar*) "collection" );
	xmlDocSetRootElement( _xmlDoc, root );
}

Collection::Collection( const Collection &c )
{
	_images = c._images;
	_selected = c._selected;

	_xmlDoc = xmlCopyDoc( c._xmlDoc, 1 );
}

Collection::~Collection()
{
	xmlFreeDoc( _xmlDoc );
}

Collection& Collection::operator =( const Collection &c )
{
	//Deconstruct and copy construct this object in place.
	this->~Collection();
	new (this) Collection( c );
	return *this;
}

void Collection::addImage( CollectionImage &image )
{
	xmlNode *root, *imageElement;
	xmlChar *fileName;

	//Create an image element in the xml document.
	root = xmlDocGetRootElement( _xmlDoc );
	imageElement = xmlNewChild( root, NULL, (const xmlChar*) "image", NULL );
	fileName = (xmlChar*) util::wcsToUtf8( image.fileName() );
	
	//Add the attribute to the image element.
	xmlNewProp(
		imageElement,
		(const xmlChar*) "file", //attribute name
		fileName //attribute value
		);

	//Append the image to the list.
	_images.push_back( image );

	delete[] fileName; //String is allocated by wcsToUtf8.
}

CollectionImage& Collection::getImage( unsigned int num )
{
	//Check if num is out of bounds.
	assert( num < size() );

	return _images[ num ];
}

unsigned int Collection::size() const
{
	return _images.size();
}

void Collection::setMetaData( int imageNum, xmlChar *xml )
{
	//TODO: Set the metadata of this image (and give a message when the xml is not valid).
}

xmlChar* Collection::metaData( int imageNum )
{
	//TODO: Give an UTF-8 string with the xml containing the metadata of a single image.
	//      This string should be allocated using new[].

	xmlChar *ret = new xmlChar[ 1 ];
	*ret = '\0';
	return ret; //Return an empty string.
}

void Collection::search()
{
	//TODO: Make a selection of the images in this collection (the _images member).
}

bool Collection::save( char *file )
{
	return xmlSaveFormatFileEnc(
		file,
		_xmlDoc,
		"UTF-8",
		TRUE
		) != -1;
}

int Collection::selected() const
{
	return _selected;
}

void Collection::setSelected( int selected )
{
	_selected = selected;
}
